"""
告警路由模块
"""
from flask import Blueprint, request, jsonify
from app.services.alert_service import AlertService
from app.utils.logger import app_logger

alert_bp = Blueprint('alert', __name__, url_prefix='/api/alerts')

@alert_bp.route('/', methods=['GET'])
def get_alerts():
    """获取告警列表"""
    try:
        # 获取查询参数
        task_id = request.args.get('task_id')
        level = request.args.get('level')
        limit = int(request.args.get('limit', 100))
        
        # 根据参数获取告警
        if task_id:
            alerts = AlertService.get_alerts_by_task(task_id, limit)
        elif level:
            alerts = AlertService.get_alerts_by_level(level, limit)
        else:
            alerts = AlertService.get_recent_alerts(limit)
        
        # 转换为字典列表
        alerts_data = [alert.to_dict() for alert in alerts]
        
        return jsonify({
            'success': True,
            'data': alerts_data
        })
    except Exception as e:
        app_logger.error(f"获取告警列表失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': '获取告警列表失败'
        }), 500

@alert_bp.route('/<alert_id>', methods=['GET'])
def get_alert(alert_id):
    """获取单个告警"""
    try:
        # 这里应该是数据库查询，暂时返回空数据
        return jsonify({
            'success': True,
            'data': {}
        })
    except Exception as e:
        app_logger.error(f"获取告警失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': '获取告警失败'
        }), 500

@alert_bp.route('/<alert_id>/resolve', methods=['POST'])
def resolve_alert(alert_id):
    """解决告警"""
    try:
        # 获取请求数据
        data = request.get_json()
        resolved_by = data.get('resolved_by')
        resolution_message = data.get('resolution_message')
        
        # 解决告警
        alert = AlertService.resolve_alert(alert_id, resolved_by, resolution_message)
        
        return jsonify({
            'success': True,
            'data': alert.to_dict() if alert else {}
        })
    except Exception as e:
        app_logger.error(f"解决告警失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': '解决告警失败'
        }), 500

@alert_bp.route('/<alert_id>', methods=['DELETE'])
def delete_alert(alert_id):
    """删除告警"""
    try:
        # 删除告警
        success = AlertService.delete_alert(alert_id)
        
        return jsonify({
            'success': success
        })
    except Exception as e:
        app_logger.error(f"删除告警失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': '删除告警失败'
        }), 500

@alert_bp.route('/check/task/<task_id>', methods=['GET'])
def check_task_alerts(task_id):
    """检查任务告警"""
    try:
        # 检查任务告警
        alerts = AlertService.check_task_alerts(task_id)
        
        # 转换为字典列表
        alerts_data = [alert.to_dict() for alert in alerts]
        
        return jsonify({
            'success': True,
            'data': alerts_data
        })
    except Exception as e:
        app_logger.error(f"检查任务告警失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': '检查任务告警失败'
        }), 500

@alert_bp.route('/check/system', methods=['GET'])
def check_system_alerts():
    """检查系统告警"""
    try:
        # 检查系统告警
        alerts = AlertService.check_system_alerts()
        
        # 转换为字典列表
        alerts_data = [alert.to_dict() for alert in alerts]
        
        return jsonify({
            'success': True,
            'data': alerts_data
        })
    except Exception as e:
        app_logger.error(f"检查系统告警失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': '检查系统告警失败'
        }), 500